﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;

using iTextSharp.text;
using iTextSharp.text.pdf;


namespace iPdf
{
    class PdfSplitter : Actor<SplitItem, PdfLetOption>
    {

        protected override void Work()
        {
            Helper.VerifyItem(workItem.Source, workItem.Destination);

            PdfReader reader = null;
            PdfCopy writer = null;
            Document document = null;
            FileStream outputStream = null;
            FileStream inputStream = null;
            try
            {
                inputStream = File.OpenRead(workItem.Source);
                reader = new PdfReader(inputStream);
                
                if (workItem.From == 1 && workItem.To == reader.NumberOfPages &&
                    pageOption.Bookmark)
                {
                    SharpHelper.ClosePdf(reader, inputStream);
                    //make sure that the handle is released
                    Helper.CollectGarbage();

                    //simply copy the file
                    File.Copy(workItem.Source, workItem.Destination);
                }

                outputStream = Helper.OpenWrite(workItem.Destination);

                document = new Document(reader.GetPageSizeWithRotation(1));
                writer = new PdfCopy(document, outputStream);
                document.Open();

                if (pageOption.Bookmark)
                {
                    Hashtable destinations = PdfPageRearranger.GetNamedDestinations(reader);
                    ArrayList bookmarks = PdfPageRearranger.ProcessBookmarks(SimpleBookmark.GetBookmark(reader), destinations,
                                                                        workItem.From, workItem.To, reader.NumberOfPages, 1 - workItem.From);
                    if (bookmarks != null)
                    {
                        writer.Outlines = bookmarks;
                    }
                }

                PdfPageRearranger.AddPages(reader, writer, workItem.From, workItem.To, workItem.Source);
            }
            finally
            {
                SharpHelper.ClosePdf(document, writer, outputStream, reader, inputStream, true);
            }
        }

    }
}
